package biznussoft.metercor;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import biznussoft.metercor.service.UnCaughtException;
import biznussoft.metercor.utils.Session;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.ui.sfnative.SalesforceActivity;

public class HomeActivity extends SalesforceActivity {

	private LocationListener mLocationListener;
	private LocationClient locationClient;
	public RestClient client;
	private RelativeLayout rLayout;
	public static HomeActivity mActivity;
	private String id;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.homepage);                           
		Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this));
		rLayout = (RelativeLayout) findViewById(R.id.rrlayout);
		mActivity = this;
	}             


	@Override 
	public void onResume() {
		rLayout.setVisibility(View.INVISIBLE);
		super.onResume();
	}		

	@Override
	public void onResume(RestClient client) {
		
		/*MyLocationManager loc = new MyLocationManager(getApplicationContext());
		loc.getLocations();*/
		this.client = client;
		mActivity.client = client;
		Session.sAccesToken = client.getAuthToken();
		Session.sInstanceUrl = client.getClientInfo().instanceUrl.toString();
		
		Log.i("NCS","UserId   :"+client.getClientInfo().userId);
		String query = "select id,FConnect__site__c from FConnect__Group_Members__c where user__c="
				+ "'" + client.getClientInfo().userId + "'";
		try {
			
			sendRequest(query);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		rLayout.setVisibility(View.VISIBLE);
	}

	public void accountAction(View v) {
		startActivity(new Intent(this, AccountsActivity.class));
	}

	public void inventoryAction(View v) {
		startActivity(new Intent(this, IInventoryActivty.class));
	}


	public void serviceAction(View v){
		startActivity(new Intent(this,ServiceOrderActivity.class));
	}

	public void logoutAction(View v){
		SalesforceSDKManager.getInstance().logout(this);
	}

	private void sendRequest(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);

		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {   
					Log.i("TPT","RestResponse   :"+result);
					String query = "select  FirstName, LastName from User where Id="+"'"+client.getClientInfo().userId+"'";
					getOwnerName(query);
					JSONObject jsonObject1 = new JSONObject(result.asString());
					JSONArray jsonArray = jsonObject1.getJSONArray("records");
					Session.sID = jsonArray.getJSONObject(0).getString("Id");
					Session.sSiteName=jsonArray.getJSONObject(0).getString("FConnect__Site__c");
					Log.i("TPT","SiteName   :"+Session.sSiteName);
					Log.i("NCS","ID s  are  :"+mActivity.client.getClientInfo().userId+" :  "+Session.sID);

				} catch (Exception e) {                                   
					Log.i("NCS","Exception in home page   :"+e.getMessage());

				}               
			}

			@Override
			public void onError(Exception exception) {

			}     
		});
	}
	private void getOwnerName(String soql) throws UnsupportedEncodingException {
		RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
		client.sendAsync(restRequest, new AsyncRequestCallback() {
			@Override
			public void onSuccess(RestRequest request, RestResponse result) {
				try {                
					Log.i("TPT","RestResponse   :"+result);
					JSONArray records = result.asJSONObject().getJSONArray("records");
					Session.sFirstName = records.getJSONObject(0).getString("FirstName");
					Session.sLastName = records.getJSONObject(0).getString("LastName");
					Session.sSiteName=records.getJSONObject(0).getString("FConnect__site__c");
					

				} catch (Exception e) {                  
					Log.i("TPT","Exception   :"+e.getMessage());
				}               
			}

			@Override
			public void onError(Exception exception) {

			}
		});
	}


	/**
	 * Called when "Logout" button is clicked. 
	 * 
	 * @param v
	 */
	/*public void onLogoutClick(View v) {
		SalesforceSDKManager.getInstance().logout(this);
	}*/

	/**
	 * Called when "Clear" button is clicked. 
	 * 
	 * @param v
	 */
	/*public void onClearClick(View v) {
		listAdapter.clear();
	}*/	

	/**           
	 * Called when "Fetch Contacts" button is clicked
	 * 
	 * @param v
	 * @throws UnsupportedEncodingException 
	 */
	/*public void onFetchContactsClick(View v) throws UnsupportedEncodingException {
        sendRequest("SELECT Name FROM Contact");
	}*/

	/**
	 * Called when "Fetch Accounts" button is clicked
	 * 
	 * @param v
	 * @throws UnsupportedEncodingException 
	 */
	/*public void onFetchAccountsClick(View v) throws UnsupportedEncodingException {
		sendRequest("SELECT Name FROM Account");
	}*/	

	class MyLocationManager implements OnConnectionFailedListener ,ConnectionCallbacks{
		public Location location;
		private Context mContext;

		public MyLocationManager(Context context) {

			mContext = context;                                    
		}

		public void getLocations() {
			Log.i("ABC","getLocations" );
			locationClient = new LocationClient(mContext, this, this);
			locationClient.connect();
		}

		public void onConnected(Bundle connectionHint) {

			LocationRequest lRequest = LocationRequest.create().setInterval(1000).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
			mLocationListener = new LocationListener() {

				public void onLocationChanged(Location location) {
					Session.sLatitude = location.getLatitude();
					Session.sLongitude = location.getLongitude();
					//new MyAsynTask().execute();
					
					Log.i("ABC","Session.sLatitude : "+Session.sLatitude );
					if(Session.sLatitude>0){
						
						new MyAsynTask().execute();
						locationClient.removeLocationUpdates(mLocationListener);
					}
				}
			};

			locationClient.requestLocationUpdates(lRequest, mLocationListener);


		}

		public void onDisconnected() {

		}

		public void onConnectionFailed(ConnectionResult result) {

		}
	}
	
	public class MyAsynTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			  try {
				  getLocationInfo(Session.sLatitude,Session.sLongitude);
	            } catch (Exception e) {
	            	Log.i("NCS", "Exception 1 is  :  " + e.getMessage());
	            }
			return null;
		}
    	
    }
  
  
  public  void getLocationInfo(Double lat,Double lon) {
	  
	  Log.i("NCS", "getLocationInfo 1 is");

		HttpGet httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+lon+"&sensor=false");
		HttpClient client = new DefaultHttpClient();
		HttpResponse response;
		StringBuilder stringBuilder = new StringBuilder();

		try {
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			InputStream stream = entity.getContent();
			int b;
			while ((b = stream.read()) != -1) {
				stringBuilder.append((char) b);
			}
		} catch (Exception e) {
			Log.i("NCS", "Exception 2 is  :  " + e.getMessage());
		} 

		JSONObject jsonObject = new JSONObject();
		
		try {
			jsonObject = new JSONObject(stringBuilder.toString());
			getGeoPoint(jsonObject);
		} catch (Exception e) {
			Log.i("NCS", "Exception 3 is  :  " + e.getMessage());
		}
		                             
		
	}
	
  
  public  void getGeoPoint(JSONObject jsonObject) {

		
		try {
			Log.i("NCS", "getGeoPoint  is");
			JSONArray results = jsonObject.getJSONArray("results");
			JSONObject js = results.getJSONObject(0);
			Session.sAddress = js.getString("formatted_address");

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.i("NCS", "Exception 4 is  :  " + e.getMessage());
		}


	}

}
